/**
 * 
 */
package com.kovell.profileo.exception;

import java.sql.SQLException;

/**
 * @author SOSSERES
 *
 */
public class EntityException extends Exception{

	public static final String NO_RESULT_EXCEPTION = "NoResultException";
	public static final String NON_UNIQUE_RESULT_EXCEPTION = "NonUniqueResultException";
	public static final String TRANSACTION_REQUIRED_EXCEPTION = "TransactionRequiredException";
	public static final String ENTITY_EXISTS_EXCEPTION = "EntityExistsException";
	public static final String ILLEGAL_STATE_EXCEPTION = "IllegalStateException";
	public static final String ILLEGAL_ARGUEMENT_EXCEPTION = "IllegalArgumentException";
	
	public static final String UNIQUE_CONSTRAINT_EXCEPTION = "UniqueConstraintException";
	public static final String CANNOT_INSERT_NULL_EXCEPTION = "CannotInsertNullException";
	
	
	private String exceptionType;
	
	private static final String PERSISTENCE_EXCEPTION = "PersistenceException";
	
	/**
	 * 
	 */
	public EntityException(Exception e) {
		super(e);
		
		System.out.println("[EntityException] Exception Class: " + e.getClass() + ". " + e.getMessage());

		this.exceptionType = e.getClass().getSimpleName();	
		
		if(PERSISTENCE_EXCEPTION.equals(exceptionType)){
			persistenceExceptionHandler(e);
		}
	}
	
	public String getExceptionType(){
		return exceptionType;
	}
	
	private void persistenceExceptionHandler(Exception e){
		int level = 1;
		
		for(Throwable t = e.getCause(); t != null; t = t.getCause()){
			System.out.println("[Persistence Exception][Level " + level++ + "] Class: " + t.getClass() + ". " + t.getMessage());
			
			if(t instanceof SQLException){
				SQLException s = (SQLException) t;
				
				
				if(s.getErrorCode() == 1) this.exceptionType = UNIQUE_CONSTRAINT_EXCEPTION;				
				if(s.getErrorCode() == 1400) this.exceptionType = CANNOT_INSERT_NULL_EXCEPTION;
						
				return;
			}
			else{
				
			}
		}
	}

}
